package org.bear.linkList;


/*
24.两两交换链表中的节点

给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。

0 1 2
1 0 2
 */
public class SwapPairs {

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = new ListNode(-1);
        ListNode p = newHead;
        ListNode odd = head.next;
        ListNode even = head;
        ListNode nextOdd = null;
        ListNode nextEven = null;
        while (odd != null && even != null) {
            if (odd.next != null) {
                nextOdd = odd.next.next;
            }
            if (even.next != null) {
                nextEven = even.next.next;
            }

            p.next = odd;
            p = p.next;
            odd = nextOdd;

            p.next = even;
            p = p.next;
            even = nextEven;
        }
        if (even!=null){
            p.next = even;
            p = p.next;
        }
        p.next = null;
        return newHead.next;
    }

    public static void main(String[] args) {
        SwapPairs s = new SwapPairs();
        ListNode listNode = s.swapPairs(ListNode.generate(new int[]{0,1,2,3}));
        System.out.println(listNode);
    }
}
